package com.yangchuang.openpicture;
import com.volcengine.ark.runtime.model.completion.chat.*;
import com.volcengine.ark.runtime.model.completion.chat.ChatCompletionContentPart.*;
import com.volcengine.ark.runtime.service.ArkService;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.TimeUnit;
import okhttp3.ConnectionPool;
import okhttp3.Dispatcher;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.Base64;
import java.io.IOException;

public class Sample {
    static String apiKey = "c09c5ea7-2297-4ce0-b1c8-7909d2bfb8de";


    static ConnectionPool connectionPool = new ConnectionPool(5, 1, TimeUnit.SECONDS);
    static Dispatcher dispatcher = new Dispatcher();
    static ArkService service = ArkService.builder()
            .dispatcher(dispatcher)
            .connectionPool(connectionPool)
            .apiKey(apiKey)
            .build();

    // Base64编码方法
    private static String encodeImage(String imagePath) throws IOException {
        byte[] imageBytes = Files.readAllBytes(Path.of(imagePath));
        return Base64.getEncoder().encodeToString(imageBytes);
    }

    public static void main(String[] args) throws Exception {

        List<ChatMessage> messagesForReqList = new ArrayList<>();

        // 本地图片路径（替换为实际路径）
        String imagePath ="D:\\sousuo\\aipicture\\微信图片_20250909193837_708_134.jpg";

        String aaa = imagePath.substring(imagePath.lastIndexOf(".")).substring(1);
        System.out.println(aaa);

        String base64Data = "data:image/" + "jpeg" + ";base64," + encodeImage(imagePath);


        // 构建消息内容（修复内容部分构建方式）
        List<ChatCompletionContentPart> contentParts = new ArrayList<>();

        // 图片部分使用builder模式
        contentParts.add(ChatCompletionContentPart.builder()
                .type("image_url")
                .imageUrl(new ChatCompletionContentPartImageURL(base64Data))
                .build());

                // 文本提示
        String prompt = """
                请严格按照以下格式分析图片，不要多余内容：
                1. name：简洁名称（10字以内）
                2. description：详细描述（50-100字）
                3. tags：标签（1-3个，中文，用中文逗号分开）""";


        // 文本部分使用builder模式
        contentParts.add(ChatCompletionContentPart.builder()
                .type("text")
                .text(prompt)
                .build());

        // 创建消息
        messagesForReqList.add(ChatMessage.builder()
                .role(ChatMessageRole.USER)
                .multiContent(contentParts)
                .build());

        ChatCompletionRequest req = ChatCompletionRequest.builder()
                .model("doubao-seed-1-6-flash-250828")
                .messages(messagesForReqList)
                //关闭深度思考
                .thinking(new ChatCompletionRequest.ChatCompletionRequestThinking("disabled"))
                .build();

        List<ChatCompletionChoice> choices = service.createChatCompletion(req)
                .getChoices();
        String content = (String) choices.get(0).getMessage().getContent();
        System.out.println(content);

        String[] aiLines = content.split("\n");

        for (String line : aiLines) {
            line = line.trim();
            if (line.startsWith("1. name：")) {
                System.out.println(line.substring("1. name：".length()).trim());
            } else if (line.startsWith("2. description：")) {
                System.out.println(line.substring("2. description：".length()).trim());
            } else if (line.startsWith("3. tags：")) {
                System.out.println(line.substring("3. tags：".length()).trim());
            }
        }


        service.shutdownExecutor();
    }
}
